//
//  ARAppLaunchController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/3/24.
//

import UIKit

import SnapKit

/// 入口页
/// 1.  先判断是否为新版本
/// 2. 自动登录
/// 3. 登录页
class ARAppLaunchController: ARBaseViewController {

    private var isFirstLaunch: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupUI()
        
        ARLogManager.logPage(.launch)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if isFirstLaunch {
            isFirstLaunch = false
            self.launchApp()
        }
    }

    // MARK: - UI
    
    private func setupUI() {
        
        view.addSubview(self.bgView)
        view.addSubview(self.logoView)
        
        bgView.snp.makeConstraints { make in
            make.edges.equalTo(view)
        }
        
        logoView.snp.makeConstraints { make in
            make.width.height.equalTo(88)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(ARHelper.screenHeight() * 0.46)
        }
        
    }
    
    // MARK: - Launch
    
    private func launchApp() {
        
        // 判断是否为第一次
        if ARAppLauncher.share.isFirstInstall {
            // 跳转至新特性
            self.showNewFeature()
            return
        }
        
        // 自动登录
        // 判断UUID是否获取成功
        if let _ = ARDevice.share.uuidResult.idfa {
            self.autoLogin()
            return
        }
        // 直接展示登录页
        ARAppLauncher.share.transitionToLoginPage()
    }
    
    private func showNewFeature() {
        // 直接addsubview - 因为newfeature界面是会直接跳转至登录页，所以无需担心内存泄漏的问题
        let newFeatureVc = ARNewFeatureController()
        self.addChild(newFeatureVc)
        self.view.addSubview(newFeatureVc.view)
        newFeatureVc.view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private func autoLogin() {
        ARUserManager.shared.autoLogin { isSuccess, err in
            if err != nil {
                // 直接跳转至登录页
                ARAppLauncher.share.transitionToLoginPage()
                return
            }
            ARAppLauncher.share.transitionToIndexPage()
        }
    }
    
    // MARK: - Lazy
    
    private lazy var bgView: UIImageView = {
        let image = UIImage(contentsOfFile: Bundle.main.path(forResource: "launch_bg.png", ofType: nil) ?? "")
        let view = UIImageView.init(image: image)
        view.contentMode = .scaleToFill
        return view
    }()
    
    private lazy var logoView: UIImageView = {
        let image = UIImage(contentsOfFile: Bundle.main.path(forResource: "logo.png", ofType: nil) ?? "")
        let view = UIImageView.init(image: image)
        view.contentMode = .scaleToFill
        return view
    }()
    
}
